<template>
  <DialogCom v-model="dialogComVisible" :title="index == 1 ? '新增部门' :  '编辑部门'"
             width="30%" submit-text="确定" @clear-form="clearForm(formRef)" @submit-form="submitForm(formRef)">
    <div class="dialogCom_wrapper">
      <el-form :model="form.data" ref="formRef" :rules="rules as FormRules" label-width="110px">
        <el-form-item label="上级部门：" prop="departmentId">
          <el-tree-select
              v-model="form.data.departmentId"
              :data="departmentTree.data"
              check-strictly
              clearable
              :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="部门名称：" prop="departmentName">
          <el-input v-model="form.data.departmentName" placeholder="请输入部门名称" clearable
                    style="width: 202px !important;"/>
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input-number
              v-model="form.data.sort"
              :min="0"
              controls-position="right"
              style="width: 202px !important;"
          />
        </el-form-item>
        <el-form-item label="状态：">
          <el-switch v-model="form.data.status" inline-prompt size="large" active-text="启用" inactive-text="停用"
                     :active-value="1" :inactive-value="0" style="height: 0"/>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="form.data.remark" type="textarea" :autosize="{minRows: 3, maxRows: 6}" show-word-limit
                    maxlength="20" style="width: 302px !important;"/>
        </el-form-item>
      </el-form>
    </div>
  </DialogCom>
</template>

<script setup lang="ts">
import DialogCom from '@/components/Dialog/index.vue'
import {ElMessage} from "element-plus";
import type {FormInstance, FormRules} from "element-plus";
import baseRequest from "@/service/baseRequest";

const props = withDefaults(defineProps<{ index: number | string, id?: number | string }>(), {
  index: '',
  id: '',
})
const emits = defineEmits(['refreshTheList'])
const {index, id} = toRefs(props)

const formRef = ref()
let dialogComVisible = ref<boolean>(false)
let form = reactive<Record<string, any>>({
  data: {
    departmentId: '',
    departmentName: '',
    status: 1,
    sort: null,
    remark: ''
  }
})
const departmentTree = reactive({
  data: []
})
const rules = reactive<FormRules>({
  departmentId: [
    {required: true, message: '请选择上级部门', trigger: 'change'}
  ],
  departmentName: [
    {required: true, message: '请输入部门名称', trigger: 'blur'}
  ],
  sort: [
    {required: true, message: '请输入排序', trigger: ['blur', 'change']}
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
        if (valid) {
          const sendData = JSON.parse(JSON.stringify(form.data))
          console.log(sendData)
          if (index.value == 1) {
            const createDepartmentRes = await baseRequest.post('/addDepartment', sendData) as any
            if (createDepartmentRes.code == 200) {
              ElMessage.success('新增部门成功')
              clearForm(formRef.value)
              dialogComVisible.value = false
              emits('refreshTheList')
            }
          } else {
            sendData.id = id.value
            const updateDepartmentRes = await baseRequest.post('/updateDepartment', sendData) as any
            if (updateDepartmentRes.code == 200) {
              ElMessage.success('更新部门成功')
              clearForm(formRef.value)
              dialogComVisible.value = false
              emits('refreshTheList')
            }
          }
        }
      }
  )
}
const clearForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.data = {
    departmentId: '',
    departmentName: '',
    status: 1,
    sort: null,
    remark: ''
  } as any
  formEl.resetFields()
}
const dropDownBoxQuery = async () => {
  const departmentListRes = await baseRequest.get('/departmentTreeList', {}) as any
  if (departmentListRes.code == 200) {
    departmentTree.data = departmentListRes.data.list
  }
}
//回显
const backShow = async () => {
  if (index.value != 1) {
    const backShowRes = await baseRequest.get('/getDepartmentInfo', {id: id.value}) as any
    if (backShowRes.code == 200) {
      form.data = backShowRes.data
    }
  }
}
defineExpose({dialogComVisible, backShow, dropDownBoxQuery})
</script>

<style lang="scss" scoped>
.dialogCom_wrapper {
  max-height: 550px;
  padding: 0 30px 0 30px;
  overflow: auto;
}

.detailForm_wrapper {
  width: 90%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
